#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <inttypes.h>
#include <time.h>
#include <genrand.h>
#include <hexstr.h>
// include cmd id function
#include <clptcCmdList.h>
#include <parmNorm.h>
#include <crcCalc.h>
// #include <clptcDevInf.h>
#if DEVICE_PLATFORM_CONFIGURE == DEVICE_PLATFORM_LINUX
#include <fileOpt.h>
#endif
#include <clptcDlgItf.h>
#include <clptcPipCmd.h>
#include <clptcHostDoCmd.h>
#include <queObj.h>

#if CLPTC_CPL_HOST_ENABLE
#define clptcDlgMgrDlgMaxNbr (5)
void clptcHostWorkFunc()
{
    // init function
    clptcFunItfStc tmpFun;
    char tmpDlgMgr[clptcDlgMgrTotalSize(clptcDlgMgrDlgMaxNbr)]; // clptcDlgMgrStc
    char tmpPkrPsr[CAL_PARSE_BUFF_PERFECT_LEN];// 8 + 24 + 12 + 12 + 8 + CLPTC_TSFR_FILE_LEN_MAX
    char tmpRcvQue[CAL_PARSE_BUFF_PERFECT_LEN + 16];
    clptcFunItfInit(&tmpFun);
    clptcFunCfgDlgMgr(&tmpFun, tmpDlgMgr, clptcDlgMgrDlgMaxNbr, clptcFunType_Host);
    clptcFunCfgPkrPsr(&tmpFun, tmpPkrPsr, sizeof(tmpPkrPsr));
    clptcFunCfgRcvQue(&tmpFun, tmpRcvQue, sizeof(tmpRcvQue));
    // cmd opt
    clptcHostDoCmdOpt tmpCmdOpt;
    clptcHostDoCmdInit(&tmpCmdOpt, &tmpFun);
    clptcPipCmdInit(&tmpCmdOpt);
    // config default addr list.
    uint8_t tmpAddrList[] = {0};
    clptcDlgMgrSetAddrs(tmpFun.lpDlgMgr, tmpAddrList, sizeof(tmpAddrList));
    while (1)
    {
        // do common command
        clptcPipCmdUp();
        clptcHostDoCmdRun(&tmpCmdOpt);
        // do function
        clptcFunItfUpdate(&tmpFun);
        usleep(10 * 1000);
    }
}
#endif
void clptcSubWorkFunc()
{
    clptcFunItfStc tmpFun;
    char tmpDlgMgr[clptcDlgMgrTotalSize(1)]; // clptcDlgMgrStc
    char tmpPkrPsr[CAL_PARSE_BUFF_PERFECT_LEN];
    clptcFunItfInit(&tmpFun);
    clptcFunCfgDlgMgr(&tmpFun, tmpDlgMgr, 1, clptcFunType_Sub);
    clptcFunCfgPkrPsr(&tmpFun, tmpPkrPsr, sizeof(tmpPkrPsr));
    while (1)
    {
        clptcFunItfUpdate(&tmpFun);
        usleep(10 * 1000);
    }
}
int main(int argl, const char **args)
{
    if (argl < 2)
    {
        logerrorc("need param, -1:host, 0-254:sub");
        return -1;
    }
    int tmpHsFlag = atoi(args[1]);
    logdebugc("input addr:%d", tmpHsFlag);
    if (!(tmpHsFlag >= -1 && tmpHsFlag < 255))
    {
        return -1;
    }
    parmNormInit(tmpHsFlag);
    parmNormIstc.addr485 = tmpHsFlag;
    parmNormSave(tmpHsFlag);
    if (tmpHsFlag == -1)
    {
#if CLPTC_CPL_HOST_ENABLE
        clptcHostWorkFunc();
#endif
    }
    else
    {
        clptcSubWorkFunc();
    }
    logdebugc("code quit");
    return 0;
}
